<template>
    <!-- 心理知识 -->
    <!-- 搜索框 -->
    <el-form :inline="true" :model="queryInfo" class="demo-form-inline">

        <el-form-item label="标题">
            <el-input v-model="queryInfo.title" placeholder="请输入标题名" clearable />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="getList">搜索</el-button>
        </el-form-item>
        <div>
            <el-button @click="toAdd" type="primary" icon="Plus" plain>新增</el-button>
        </div>
    </el-form>
    <!-- 信息展览 -->
    <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column prop="id" label="id" width="50" />
        <el-table-column prop="title" label="心理知识标题" width="120" />
        <el-table-column prop="simplyIntroduce" label="简介" width="120" />
        <el-table-column prop="img" label="图片" width="120">
            <template #default="scope">
                <el-image v-if="scope.row.img" style="width: 100px; height: 100px" :src="url + scope.row.img"
                    :fit="fit" />
            </template>
        </el-table-column>
        <el-table-column prop="content" label="详情内容" width="120">
            <template #default="scope">
                <div class="ellipsis-text">{{ scope.row.content }}</div>
            </template>    
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="100">
            <template #default="scope">
                <el-button link type="primary" size="small" @click="toView(scope.row)">查看详情内容</el-button>
                <el-button link type="primary" size="small" @click="toEdit(scope.row)">修改</el-button>
                <el-button link type="primary" @click="onDel(scope.row.id)" size="small">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination style="margin-top: 10px;" v-model:current-page="queryInfo.pageNum"
        v-model:page-size="queryInfo.pageSize" :page-sizes="[1, 5, 10, 20]" size="default" background="false"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    <!-- 添加编辑弹框 -->
    <el-dialog v-model="saveOrUpdateVisible" :title="saveOrUpdateTitle" width="500">
        <el-form :model="heartKnowledge">
            <el-form-item label="心理知识标题">
                <el-input v-model="heartKnowledge.title" autocomplete="off" />
            </el-form-item>
            <el-form-item label="简介">
                <el-input v-model="heartKnowledge.simplyIntroduce" autocomplete="off" />
            </el-form-item>
            <el-form-item label="图片">
                <el-upload v-model:file-list="fileList" class="avatar-uploader" list-type="picture-card"
                    action="http://localhost:8080/file/upload" :on-success="handleAvatarSuccess">
                    <img v-if="img" :src="img" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="详情内容">
                <TEditor :modelValue="heartKnowledge.content" @update:modelValue="handleContentUpdate"></TEditor>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="close">取消</el-button>
                <el-button type="primary" @click="saveOrUpdate">
                    {{ saveOrUpdateTitle }}
                </el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 详情内容弹出框 -->
    <el-dialog v-model="viewVisible" :title="viewTitle" width="500">
        <el-form-item label="文章详情">
            <TEditor :modelValue="heartKnowledge.content" @update:modelValue="handleContentUpdate" readonly :toolbar="false"></TEditor>
        </el-form-item>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="closeView">取消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus'

import TEditor from '@/components/TEditor.vue';
// 富文本
const handleContentUpdate = (value) => {
    heartKnowledge.value.content = value;
};
// 查看详情
const toView = (row) => {
    viewTitle.value = '文章详情'
    viewVisible.value = true
    heartKnowledge.value = { ...row }
}
// 关闭详情弹出框
const closeView = () => {
    viewVisible.value = false
    heartKnowledge.value = {
        content: ''
    }
}

const viewVisible = ref(false)
const viewTitle = ref('文章详情')
const viewFree = ref({
    content: ''
})

// 图片上传
const img = ref('')
const fileList = ref([])
// 图片上传
const handleAvatarSuccess = (response, uploadFile) => {
    img.value = URL.createObjectURL(uploadFile.raw)
  // 上传成功，则需要把返回的数据复制给
  heartKnowledge.value.img = response.data
}

// 修改或添加
const saveOrUpdateVisible = ref(false)
const heartKnowledge = ref({
    id: '',
    title: '',
    simplyIntroduce: '',
    img: '',
    content: ''
})
const saveOrUpdateTitle = ref('添加')
// 去修改的界面
const toEdit = row => {
    saveOrUpdateTitle.value = '修改'
    saveOrUpdateVisible.value = true
    heartKnowledge.value = row
    console.log(heartKnowledge.value);
    // 把图片的名称和路径放入到fileList中
    fileList.value = [
        {
            url: url.value + heartKnowledge.value.img,
            name: '000'
        }
    ]
}
// 定义一个图片路径
const url = ref('http://localhost:8080/file/downLoad?fileName=')
// 定义一个图片缩放
const fit = ref('cover')
// 去添加的界面
const toAdd = row => {
    saveOrUpdateTitle.value = '添加'
    saveOrUpdateVisible.value = true
    heartKnowledge.value = {
        id: '',
        title: '',
        simplyIntroduce: '',
        img: '',
        content: ''
    }
}
// 取消修改或保存
const close = () => {
    saveOrUpdateVisible.value = false
    // 请求图片展示
    img.value = ''
    fileList.value = []
    // 清空表单
    heartKnowledge.value = {
        id: '',
        title: '',
        simplyIntroduce: '',
        img: '',
        content: ''
    }
}
// 保存或修改
const saveOrUpdate = () => {
    if (saveOrUpdateTitle.value == '添加') {
    
        //调用后端接口添加
        axios.post('/heartKnowledge', heartKnowledge.value)
            .then((resp) => {
                let result = resp.data
                if (result.code == 1) {
                    // 重新获取列表
                    getList()
                    ElMessage.success('添加成功')
                    saveOrUpdateVisible.value = false
                } else {
                    ElMessage.error('添加失败')
                }
            })
            .catch((error) => {
                console.error('添加时发生错误:', error);
                ElMessage.error('添加失败');
            });
    } else {
        //调用后端接口修改
        axios.put('/heartKnowledge', heartKnowledge.value)
            .then(resp => {
                let result = resp.data
                if (result.code == 1) {
                    // 重新获取列表
                    getList()
                    ElMessage.success('修改成功')
                    saveOrUpdateVisible.value = false
                } else {
                    ElMessage.error('修改失败')
                }
            })
            .catch((error) => {
                console.error('修改文章时发生错误:', error);
                ElMessage.error('修改文章失败');
            });
    }
    // 关闭弹框
    saveOrUpdateVisible.value = false
    // 请求图片展示
    fileList.value = []
    img.value = ''
    // 清空表单
    heartKnowledge.value = {
        id: '',
        title: '',
        simplyIntroduce: '',
        img: '',
        content: ''
    }
}


const tableData = ref([])
//   定义一个方法当页面加载时就调用
onMounted(() => {
    getList()
})
//   定义一个全局参数变量
const queryInfo = ref({
    pageNum: 1,
    pageSize: 5,
    id: '',
    title: '',
    simplyIntroduce: '',
    img: '',
    content: ''
})
// 定义一个数据总条数
const total = ref(0)
//   定义一个方法，用于获取文章列表
const getList = () => {
    // 使用axios调用后端接口获取数据
    axios.get('/heartKnowledge/selectAll', {
        params: queryInfo.value
    })
        .then((resp) => {
            let result = resp.data // 后端返回的数据
            if (result.code == 1) {
                total.value = result.data.total
                tableData.value = result.data.list
            } else {
                ElMessage.error('获取列表失败')
            }
        })
        .catch((error) => {
            console.error('获取列表时发生错误:', error);
            ElMessage.error('获取列表失败');
        });
}
// 分页
const handleSizeChange = (val) => {
    queryInfo.value.pageSize = val;
    queryInfo.value.pageNum = 1;
    getList();
}
const handleCurrentChange = (val) => {
    queryInfo.value.pageNum = val;
    getList();
}

// 删除
const onDel = id => {
    ElMessageBox.confirm(
        '真的要删除吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            //调用后端接口删除
            axios.delete('/heartKnowledge/' + id)
                .then((resp) => {
                    let result = resp.data
                    if (result.code == 1) {
                        // 重新获取列表
                        getList()
                        ElMessage.success('删除成功')
                        getList()
                    } else {
                        ElMessage.error('删除失败')
                    }
                })
                .catch((error) => {
                    console.error('删除文章时发生错误:', error);
                    ElMessage.error('删除失败');
                });
        })
        .catch(() => { })
}

</script>

<style>
/* 省略号格式 */
.ellipsis-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
  /* 根据表格列宽调整 */
}
.avatar-uploader .el-upload {
    border: 1px dashed black;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    border: 1px solid black;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.demo-form-inline .el-input {
    --el-input-width: 220px;
}

.demo-form-inline .el-select {
    --el-select-width: 220px;
}
</style>